<template>
    <div class="app-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="平台ID">
                <el-input size="mini" v-model="queryParams.platformId" placeholder="平台ID"></el-input>
            </el-form-item>
            <el-form-item label="英文名称">
                <el-input size="mini" v-model="queryParams.platformName" placeholder="平台英文名称"></el-input>
            </el-form-item>
            <el-form-item label="中文名称">
                <el-input size="mini" v-model="queryParams.platformNameZh" placeholder="平台中文名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="mini" @click="handleQuery">查询</el-button>
                <el-button size="mini" @click="handleResetQuery">重置</el-button>
            </el-form-item>
        </el-form>
    <el-row :gutter="5">
        <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini">添加</el-button>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--            <el-button icon="el-icon-delete" type="danger" @click="handleDelete" size="mini">删除选中</el-button>-->
<!--        </el-col>-->
    </el-row>
    <el-table
            :data="tableData"
            stripe
            border

            style="width: 100%"
            :cell-style="{padding:'3px'}"
    >
<!--        <el-table-column type="selection" width="55"></el-table-column>-->
        <el-table-column prop="platformId" label="平台ID"></el-table-column>
        <el-table-column prop="platformName" label="平台英文名称"></el-table-column>
        <el-table-column prop="platformNameZh" label="平台中文名称"></el-table-column>
        <el-table-column prop="description" label="平台简介"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="状态">
            <template slot-scope="scope">
                <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                ></el-switch>
            </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="160">
            <template slot-scope="scope">
                <el-tooltip content="导入用户" placement="top">
                    <el-button @click="handleImport(scope.row)" type="primary" size="small" icon="el-icon-user" circle></el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small" icon="el-icon-edit" circle></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                    <el-button @click="handleDeleteRow(scope.row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
                </el-tooltip>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            layout="total, prev, pager, next"
            v-show="total>0"
            :total="total"
            :page-size="queryParams.limit"
            @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="英文名称" prop="platformName">
                        <el-input v-model="form.platformName" placeholder="请输入英文名称" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="中文名称" prop="platformNameZh">
                        <el-input v-model="form.platformNameZh" placeholder="平台中文名称" maxlength="20"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="简介" prop="description">
                        <el-input type="textarea" v-model="form.description" placeholder="请输入简介" maxlength="300"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload
                    ref="upload"
                    :limit="1"
                    accept=".xlsx, .xls"
                    :headers="upload.headers"
                    :action="upload.url + '?platformName=' + upload.platformName"
                    :disabled="upload.isUploading"
                    :on-progress="handleFileUploadProgress"
                    :on-success="handleFileSuccess"
                    :auto-upload="false"
                    drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import {list,del,get,add,update} from "@/api/platform/platform";
    import {getToken} from "@/utils/session_storage";
    export default {
        name: "Dept",
        data() {
            return {
                queryParams: {
                    page: 1,
                    limit: 10
                },
                total: 0,
                tableData: [],
                multipleSelection: [],
                title: '',
                // 添加/修改表单参数
                form: {
                },
                // 用户导入参数
                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的用户数据
                    updateSupport: 0,
                    //
                    platformName: '',
                    // 设置上传的请求头部
                    headers: { "token":  getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/ttxs/common/user/importData"
                },
                // 添加/修改表单校验
                rules: {
                    platformName: [
                        {required: true, message: "英文名称不能为空", trigger: "blur"}
                    ],
                    platformNameZh: [
                        {required: true, message: "中文名称不能为空", trigger: "blur"}
                    ],
                    description: [
                        {required: true, message: "简介不能为空", trigger: "blur"},
                    ]
                },
                // 是否显示弹出层
                open: false,
            }
        },
        created() {
            this.getList()
        },
        watch: {
            // 删除最后一页所有数据时，回到上一页
            total(val) {
                if(val == (this.queryParams.page-1) * this.queryParams.limit){
                    this.queryParams.page--
                    this.getList()
                }
            }
        },
        methods: {
            handleQuery() {
                this.getList()
            },
            handleResetQuery() {
                this.queryParams = {
                    platformId: undefined,
                    platformName: undefined,
                    platformNameZh: undefined,
                    page: 1,
                    limit: 10
                }
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            reset() {
                this.form = {
                    platformId: undefined,
                    platformName: undefined,
                    platformNameZh: undefined,
                    description: undefined,
                    status: undefined
                }
            },
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if(valid) {
                        if(this.form.platformId != undefined) {
                            update(this.form).then(()=>{
                                this.$message({message:'修改成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        } else {
                            this.form.status = 0; // 默认启用状态
                            add(this.form).then(()=>{
                                this.$message({message:'添加成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        }
                    }
                })
            },
            getList() {
                list(this.queryParams).then(response => {
                    this.tableData = response.data.records
                    this.total = response.data.total
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
                console.log(this.multipleSelection);
            },
            handleCurrentChange(val) {
                this.queryParams.page = val;
                this.getList()
            },
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加平台";
            },
            handleView(row) {
                get(row.platformId).then(resp=>{
                    console.log(resp);
                })
            },
            handleEdit(row) {
                this.reset();
                get(row.platformId).then(resp=>{
                    this.form = resp.data;
                    this.open = true;
                    this.title = "修改平台";
                })
            },
            handleDeleteRow(row) {
                this.$confirm('确定删除【' + row.platformName + '】吗?此操作将删除该平台下所有数据（包括用户、角色、菜单、部门等）且无法恢复！你可以先试试停用该平台', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 再次确认删除
                    this.$prompt('你正在删除平台【' + row.platformName + '】!请再次输入“确定删除”，以免误操作', '删除警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputValidator: function(value) {
                            return value == '确定删除'
                        },
                        inputErrorMessage: '如果确定要删除数据，请输入“确定删除”'
                    }).then(() => {
                        let idList = row.platformId;
                        del(idList).then(resp => {
                            this.$message({
                                type: 'success',
                                message: resp.msg
                            });
                            this.getList()
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '取消删除'
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleDelete() {
                if(this.multipleSelection.length == 0) {
                    this.$alert('请至少选中一条记录')
                } else {
                    this.$confirm('确定删除选中的记录吗, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let idList = this.multipleSelection.map(row=>row.platformId).join(",");
                        del(idList).then(resp => {
                            this.$message({
                                type: 'success',
                                message: resp.msg
                            });
                            this.getList()
                        })

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            handleStatusChange(row) {
                let text = row.status === "0" ? "启用" : "停用";
                this.$confirm('确认要"' + text + '""' + row.platformName + '"部门吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return update({platformId:row.platformId, status:row.status});
                }).then(() => {
                    this.$message({message: text + "成功", type:'success'})
                }).catch(function() {
                    row.status = row.status === "0" ? "1" : "0";
                });
            },
            handleImport(row) {
                this.upload.title = "用户导入";
                this.upload.open = true;
                this.upload.platformName = row.platformName
            },
            /** 下载模板操作 */
            importTemplate() {
                this.download('ttxs/common/user/importTemplate', {
                }, `user_template_${new Date().getTime()}.xlsx`)
            },
            // 文件上传中处理
            // eslint-disable-next-line no-unused-vars
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            // eslint-disable-next-line no-unused-vars
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            }
        }
    }
</script>
